package chapter3;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author ycj
 * @version 1.0
 * @description: TODO
 * @date 2022/5/17
 */

//读写锁的使用

public class Source3_4 {
    private static int data=0;
    private final static ReadWriteLock readWriteLock=new ReentrantReadWriteLock();
    private final static Lock readLock=readWriteLock.readLock();//读锁
    private final static Lock writeLock=readWriteLock.writeLock();//写锁
    public static void main(String[] args) {
        Thread[] threads=new Thread[10];

        for(int i=0;i<5;i++){
            threads[i]=new Thread(()->{
                readLock.lock();
                try{
                    System.out.println(Thread.currentThread().getName()+"获取读锁"+" data="+data);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    readLock.unlock();
                }
            });
        }

        for(int i=5;i<10;i++){
            threads[i]=new Thread(()->{
                writeLock.lock();
                try{
                    System.out.println(Thread.currentThread().getName()+"获取写锁");
                    data++;
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    writeLock.unlock();
                }
            });
        }

        threads[0].start();
        threads[5].start();
        threads[1].start();
    }

}

